/*
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2024-03-30 18:01:42
 * @LastEditTime: 2024-04-02 11:28:09
 * @FilePath: \electron-wallpaper\src\main\index.js
 * @Description:
 *
 */
import { electronApp, is, optimizer } from '@electron-toolkit/utils'
import { app, BrowserWindow, dialog, ipcMain, Menu, shell, Tray } from 'electron'
import fs from 'fs'
import { join, resolve } from 'path'
import wallpaper from 'wallpaper'
import icon from '../../resources/icon.png?asset'
function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    width: 400,
    height: 370,
    show: false,
    autoHideMenuBar: true,
    // skipTaskbar: true,
    // maximizable: false,
    movable: true,
    resizable: false,
    fullscreenable: false,
    titleBarStyle: 'hidden',
    ...(process.platform === 'linux' ? { icon } : {}),
    webPreferences: {
      preload: join(__dirname, '../preload/index.js'),
      sandbox: false
    },
    // 隐藏窗体logo

    alwaysOnTop: false, //设置窗口置顶
    useContentSize: true
  })

  // 设置边框
  // 开启控制台
  // mainWindow.webContents.openDevTools()
  // 设置窗口位置居中
  mainWindow.center()
  // console.log(width, height)
  // 设置窗口位置
  // mainWindow.setBounds({
  //   x: width - mainWindow.webContents.width,
  //   y: mainWindow.webContents.height
  // })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }
  // mainWindow.webContents.openDevTools(mainWindow)

  mainWindow.on('ready-to-show', () => {
    mainWindow.show()
  })

  // mainWindow.webContents.setWindowOpenHandler((details) => {
  //   shell.openExternal(details.url)
  //   return { action: 'deny' }
  // })

  // HMR for renderer base on electron-vite cli.
  // Load the remote URL for development or the local html file for production.
  if (is.dev && process.env['ELECTRON_RENDERER_URL']) {
    mainWindow.loadURL(process.env['ELECTRON_RENDERER_URL'])
  } else {
    mainWindow.loadFile(join(__dirname, '../renderer/index.html'))
  }

  return mainWindow
}

const SUPPORT_URL = 'http://wwww.baidu.com'

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(() => {
  // Set app user model id for windows
  electronApp.setAppUserModelId('wallpaper')

  // Default open or close DevTools by F12 in development
  // and ignore CommandOrControl + R in production.
  // see https://github.com/alex8088/electron-toolkit/tree/master/packages/utils
  app.on('browser-window-created', (_, window) => {
    optimizer.watchWindowShortcuts(window)
  })

  // IPC test
  ipcMain.on('ping', () => console.log('pong'))

  let mainWindow = createWindow()

  ipcMain.handle('wallpaper:setWallpaper', async (event, url) => {
    // 注意相对路径 当前目录 拼接文件文件名称就可以了
    const localFile = resolve(__dirname, '../../resources/wallpaper/' + url).replace(
      'app.asar',
      'app.asar.unpacked'
    )
    wallpaper.set(localFile, { screen: 'all', scale: 'auto' })
  })

  // eslint-disable-next-line no-unused-vars
  ipcMain.handle('wallpaper:selectWallpaper', async (event) => {
    const result = await dialog.showOpenDialogSync(mainWindow, {
      properties: ['openFile'],
      filters: [{ name: 'Images', extensions: ['jpg', 'jpeg', 'png', 'gif'] }]
    })
    if (result) {
      // 将文件 复制到 resources/wallpaper 目录下
      let url = result[0]
      let target = resolve(
        __dirname,
        '../../resources/wallpaper/' + result[0].split('\\').pop()
      ).replace('app.asar', 'app.asar.unpacked')

      copyFile(
        url,
        target,
        (err, e) => {
          // 弹窗警告
          if (err) {
            dialog.showMessageBox({
              type: 'error',
              title: '错误',
              message: err + e.toString()
            })
          }
        },
        () => {
          wallpaper.set(target, {
            screen: 'all',
            scale: 'auto'
          })
          // 弹窗提示
          // dialog.showMessageBox({
          //   type: 'info',
          //   title: '成功',
          //   message: '图片已复制到 resources/wallpaper 目录下'
          // })
        }
      )
    }
  })

  let timer = null //外部变量存放定时器

  // eslint-disable-next-line no-unused-vars
  ipcMain.handle('wallpaper:loopWallpaper', async (event, isOpen, interval = 2000) => {
    // 该文件下 文件的图片类型文件个数
    const files = fs.readdirSync(
      resolve(__dirname, '../../resources/wallpaper/').replace('app.asar', 'app.asar.unpacked')
    )
    // console.log(files)
    if (files) {
      if (files.length > 0) {
        let maptemp = files.map((file) =>
          resolve(__dirname, '../../resources/wallpaper/' + file).replace(
            'app.asar',
            'app.asar.unpacked'
          )
        )

        let index = -1
        if (isOpen) {
          timer = setInterval(() => {
            index < files.length - 1 ? index++ : (index = 0)
            // console.log(maptemp[index], index, 'ssssssssss')
            wallpaper.set(maptemp[index], {
              screen: 'all',
              scale: 'auto'
            })
          }, interval)
        } else {
          if (timer) {
            clearInterval(timer)
          }
        }
      }
    }
  })

  // eslint-disable-next-line no-unused-vars
  ipcMain.handle('wallpaper:getWallpaperList', (event) => {
    const files = fs.readdirSync(
      resolve(__dirname, '../../resources/wallpaper/').replace('app.asar', 'app.asar.unpacked')
    )
    if (files) {
      if (files.length > 0) {
        let filetemp = files.map((file) =>
          resolve(__dirname, '../../resources/wallpaper/' + file).replace(
            'app.asar',
            'app.asar.unpacked'
          )
        )
        return filetemp
      }
    }
    return []
  })

  ipcMain.handle('win:quit', () => {
    // 关闭程序
    app.quit()
  })

  // 打开外链
  // eslint-disable-next-line no-unused-vars
  ipcMain.on('openExternal', (event, url) => {
    shell.openExternal(url)
  })

  // 最小化窗口
  // eslint-disable-next-line no-unused-vars
  ipcMain.on('win:minimize', (event) => {
    mainWindow.minimize()
  })

  // 窗口置顶
  // eslint-disable-next-line no-unused-vars
  ipcMain.on('win:toggleTop', (event) => {
    mainWindow.setAlwaysOnTop(!mainWindow.isAlwaysOnTop())
  })

  app.on('activate', function () {
    // On macOS it's common to re-create a window in the app when the
    // dock icon is clicked and there are no other windows open.
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })

  // 随机设置一张图片
  function randomWallpaper() {
    const files = fs.readdirSync(
      resolve(__dirname, '../../resources/wallpaper/').replace('app.asar', 'app.asar.unpacked')
    )
    if (files) {
      // 获取随机数
      let index = Math.floor(Math.random() * files.length)
      // 注意相对路径 当前目录 拼接文件文件名称就可以了
      const localFile = resolve(__dirname, '../../resources/wallpaper/' + files[index]).replace(
        'app.asar',
        'app.asar.unpacked'
      )
      wallpaper.set(localFile, { screen: 'all', scale: 'auto' })
    }
  }

  let tray = new Tray(icon)
  const contextMenu = Menu.buildFromTemplate([
    { label: '问题反馈', click: () => shell.openExternal(SUPPORT_URL) },
    { label: '随机壁纸', click: () => randomWallpaper() },
    { type: 'separator' },
    { label: '退出应用', role: 'quit' }
  ])
  tray.setToolTip('小杨壁纸')
  tray.setContextMenu(contextMenu)
})

// 复制文件
function copyFile(src, target, errorCallback, successCallback) {
  // 源图片文件路径
  const sourcePath = src

  // 目标路径
  const destinationPath = target

  // 使用 fs.createReadStream 创建可读流
  const readStream = fs.createReadStream(sourcePath)

  // 使用 fs.createWriteStream 创建可写流
  const writeStream = fs.createWriteStream(destinationPath)

  // 监听可读流的 'data' 事件，当有数据可读时触发
  readStream.on('data', (chunk) => {
    // 将数据写入可写流
    writeStream.write(chunk)
  })

  // 监听可读流的 'end' 事件，当所有数据读取完毕时触发
  readStream.on('end', () => {
    // 关闭可写流
    writeStream.end()

    if (successCallback) successCallback('图片复制完成')
  })

  // 监听可读流的 'error' 事件，当读取过程中发生错误时触发
  readStream.on('error', (err) => {
    if (errorCallback) errorCallback('读取文件时出错:', err)
  })

  // 监听可写流的 'error' 事件，当写入过程中发生错误时触发
  writeStream.on('error', (err) => {
    if (errorCallback) errorCallback('写入文件时出错:', err)
  })
}

// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

// In this file you can include the rest of your app"s specific main process
// code. You can also put them in separate files and require them here.
